package com.abel.bigwater.kmgw

import com.abel.bigwater.dataserver.model.PojoHelper
import com.abel.bigwater.dataserver.model.hgd.HgdUdpData
import com.abel.bigwater.kmgw.dao.FlowDao
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import org.slf4j.LoggerFactory

class IwgServerHandler(val iwgDao: FlowDao) : ChannelInboundHandlerAdapter() {
    override fun channelActive(ctx: ChannelHandlerContext?) {
        lgr.info("Got connection from ${ctx?.channel()?.remoteAddress()}")
    }


    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        lgr.info("$msg from ${ctx?.channel()?.remoteAddress()}")

        when {
            msg is HgdUdpData -> {
                val fd = PojoHelper.toPojo(msg, null)
                iwgDao.upsert(fd)
            }
            else -> lgr.warn("other packet type: ${msg?.javaClass}")
        }

        ctx?.writeAndFlush(ctx.alloc().buffer().writeBytes(OK_RESPONSE.toByteArray(Charsets.ISO_8859_1)))
    }

    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        lgr.info("try to reset connection caused by exception from ${ctx?.channel()?.remoteAddress()}")
        ctx?.close()
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(KmingServerHandler::class.java)

        const val OK_RESPONSE = "@222\r\n"
    }
}